package com.example.tetris.slice;

import com.example.tetris.ResourceTable;
import com.example.tetris.beans.MyCommondialog;
import com.example.tetris.beans.MyToastdialog;
import com.example.tetris.beans.RecordingTable;
import com.example.tetris.beans.RecordingProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class RecordingSlice extends AbilitySlice implements TabList.TabSelectedListener {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
    private Uri uri = Uri.parse("dataability:///com.example.tetris.SQLite");
    private Uri uri_df = Uri.parse("dataability:///com.example.tetris.SQLite_df");
    //判断游戏模式
    String game_mode;
    DataAbilityHelper helper = DataAbilityHelper.creator(this);

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_game_recording);
        game_mode = intent.getStringParam("mode_flag");

        Text text_mode = (Text) findComponentById(ResourceTable.Id_recording_mode);
        if (Objects.equals(game_mode, "classic")) {
            text_mode.append("经典");
        } else if (Objects.equals(game_mode, "difficulty")) {
            text_mode.append("困难");
        }


        //渲染列表：将获取到的数据按照Item布局，显示到列表中ListContainer
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        // 构造查询条件,根据时间升序
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.orderByAsc("seconds");
        // 进行查询
        ResultSet resultSet = null;
        try {
            if (Objects.equals(game_mode, "classic")) {
                resultSet = helper.query(uri, null, predicates);
            } else if (Objects.equals(game_mode, "difficulty")) {
                resultSet = helper.query(uri_df, null, predicates);
            }

        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        //查询到的数据装载到列表
        List<RecordingTable> data = getData(resultSet);
        //数据适配器：将data中的一条数据，渲染到一个Item的布局视图，再将渲染后的Item载入到listcontainer列表中
        RecordingProvider recordingProvider = new RecordingProvider(data, this);
        listContainer.setItemProvider(recordingProvider);

        //初始化TabList
        initTabList();


        //返回按钮
        Button button = (Button) findComponentById(ResourceTable.Id_button_back);
        if (button != null) {
            button.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    terminateAbility();
                }
            });
        }
        //清除数据按钮
        Button button_clear = (Button) findComponentById(ResourceTable.Id_button_clear);
        if (button_clear != null) {
            button_clear.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {

                    //把cmddialog中的布局加载到内存中，交给弹窗并展示出来
                    //加载xml文件并获得一个布局文件，LatoutScatter为布局的工具类
                    //parse方法：加载一个xml文件，返回一个布局对象 参数一：要加载的xml文件 参数二：改xml文件是否跟其他xml文件有关。如果是无关独立的，就写null 参数三：如果文件是独立的，那么就写false
                    DirectionalLayout dl = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                            .parse(ResourceTable.Layout_cmddialog_clear, null, false);

                    MyCommondialog commondialog = new MyCommondialog(getContext(), dl);

                    //要给布局里面的按钮文本设置事件或内容
                    //此时需要用dl去调用，表示获取的是dl这个布局里面的组件
                    Text title = (Text) dl.findComponentById(ResourceTable.Id_title);
                    Button submit = (Button) dl.findComponentById(ResourceTable.Id_submit);
                    Button cancel = (Button) dl.findComponentById(ResourceTable.Id_cancel);
                    //此时需要给两个按钮添加点击事件
                    //确认事件
                    submit.setClickedListener(new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {
                            //清除数据库中数据
                            // 构造条件 predicates
                            DataAbilityPredicates predicates = new DataAbilityPredicates();

                            predicates.clear();
                            try {
                                if (Objects.equals(game_mode, "classic")) {
                                    helper.delete(uri, predicates);
                                } else if (Objects.equals(game_mode, "difficulty")) {
                                    helper.delete(uri_df, predicates);
                                }
                                commondialog.destroy();
                                MyToastdialog.showTip(getContext(), "已删除");
                                terminate();
                                terminateAbility();
                            } catch (DataAbilityRemoteException e) {
                                e.printStackTrace();
                            }

                        }
                    });
                    //取消事件
                    cancel.setClickedListener(new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {
                            //关闭弹框
                            commondialog.destroy();

                        }
                    });
                }
            });
        }
    }


    //初始化TabList
    private void initTabList() {
        TabList tablist = (TabList) findComponentById(ResourceTable.Id_recording_tablist);
        String[] tabTexts = {"全部数据", "得分排序", "时长排序"};
        for (int i = 0; i < tabTexts.length; i++) {
            TabList.Tab tab = tablist.new Tab(this);
            tab.setText(tabTexts[i]);
            tablist.addTab(tab);
            if (i == 0) {
                tab.select();
            }
        }
        //tablist事件监听
        tablist.addTabSelectedListener(this);

    }


    //item数据获取
    private List<RecordingTable> getData(ResultSet resultSet) {
        List<RecordingTable> recordingList = new ArrayList<>();
        while (resultSet.goToNextRow()) {
            RecordingTable recordingTable = new RecordingTable(resultSet.getString(1), resultSet.getInt(2), resultSet.getString(3));
            recordingList.add(recordingTable);
        }
        return recordingList;
    }

    //tablist事件监听函数
    @Override
    public void onSelected(TabList.Tab tab) {
        int position = tab.getPosition();//索引
        if (position == 0) {
            System.out.println("----------->>>" + position);
            //渲染列表：将获取到的数据按照Item布局，显示到列表中ListContainer
            ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
            // 构造查询条件 predicates
            DataAbilityPredicates predicates = new DataAbilityPredicates();
            predicates.greaterThan("id", 0);
            // 进行查询
            ResultSet resultSet = null;
            try {
                if (Objects.equals(game_mode, "classic")) {
                    resultSet = helper.query(uri, null, predicates);
                } else if (Objects.equals(game_mode, "difficulty")) {
                    resultSet = helper.query(uri_df, null, predicates);
                }
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }
            //查询到的数据装载到列表
            List<RecordingTable> data = getData(resultSet);
            //数据适配器：将data中的一条数据，渲染到一个Item的布局视图，再将渲染后的Item载入到listcontainer列表中
            RecordingProvider recordingProvider = new RecordingProvider(data, this);
            listContainer.setItemProvider(recordingProvider);


        } else if (position == 1) {
            System.out.println("----------->>>" + position);
            //渲染列表：将获取到的数据按照Item布局，显示到列表中ListContainer
            ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
            // 构造查询条件,根据得分降序排列
            DataAbilityPredicates predicates = new DataAbilityPredicates();
            predicates.orderByDesc("score");
            // 进行查询
            ResultSet resultSet = null;
            try {
                if (Objects.equals(game_mode, "classic")) {
                    resultSet = helper.query(uri, null, predicates);
                } else if (Objects.equals(game_mode, "difficulty")) {
                    resultSet = helper.query(uri_df, null, predicates);
                }
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }

            //查询到的数据装载到列表
            List<RecordingTable> data = getData(resultSet);
            //数据适配器：将data中的一条数据，渲染到一个Item的布局视图，再将渲染后的Item载入到listcontainer列表中
            RecordingProvider recordingProvider = new RecordingProvider(data, this);
            listContainer.setItemProvider(recordingProvider);


        } else if (position == 2) {
            System.out.println("----------->>>" + position);
            //渲染列表：将获取到的数据按照Item布局，显示到列表中ListContainer
            ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
            // 构造查询条件,根据时间升序
            DataAbilityPredicates predicates = new DataAbilityPredicates();
            predicates.orderByAsc("seconds");
            // 进行查询
            ResultSet resultSet = null;
            try {
                if (Objects.equals(game_mode, "classic")) {
                    resultSet = helper.query(uri, null, predicates);
                } else if (Objects.equals(game_mode, "difficulty")) {
                    resultSet = helper.query(uri_df, null, predicates);
                }
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }

            //查询到的数据装载到列表
            List<RecordingTable> data = getData(resultSet);
            //数据适配器：将data中的一条数据，渲染到一个Item的布局视图，再将渲染后的Item载入到listcontainer列表中
            RecordingProvider recordingProvider = new RecordingProvider(data, this);
            listContainer.setItemProvider(recordingProvider);

        }


    }

    @Override
    public void onUnselected(TabList.Tab tab) {

    }

    @Override
    public void onReselected(TabList.Tab tab) {

    }
}


